package com.example.bjsfpost.utils;

import okhttp3.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class EmailOkHttpUtil {
    // 调用案例
    public static void main(String[] args) throws IOException {
        String url = "http://192.188.2.211/platform/email/email/send";
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBOYW1lIjoidGVzdCIsImV4cCI6MTcwMTE2NzMxMH0.tQBMSz02DJRliGffuP4EPq6KzK_ThA3E9wJ94F7Y6fM";
        Map<String,Object> params = new HashMap<>();
        params.put("env","TEST");
        params.put("subject","测试api");
        params.put("htmlContent","测试apiHtmlContent");
        params.put("tos","pangy-v@sf.local");
//        params.put("ccs","pangy-v@sf.local,wanglibin-v@sf.local");

        // 这里附件只是做个示例，web项目中，可以直接从 请求中获取文件名，类型，字节
        List<EmailAttachment> attachmentList = new ArrayList<>();
        EmailAttachment emailAttachment = new EmailAttachment();
        File file = new File("C:\\Users\\pangy-v\\Desktop\\test.png");
        FileInputStream is = new FileInputStream(file);
        byte[] bytes = new byte[Integer.parseInt(file.length() + "")];
        is.read(bytes);
        emailAttachment.setFileName("test.png");
        emailAttachment.setContentType("image/png");
        emailAttachment.setFile(bytes);
        attachmentList.add(emailAttachment);

        String s = httpPost(url, token, params,attachmentList);
        System.out.println(s);
    }

    public static String httpPost(String url, String token, Map<String,Object> params, List<EmailAttachment> emailAttachmentList) throws IOException {
        OkHttpClient client = new OkHttpClient();
        // 构建请求体
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            builder.addFormDataPart(entry.getKey(),entry.getValue().toString());
        }
        // 如果有附件
        if (emailAttachmentList != null && emailAttachmentList.size() > 0){
            for (EmailAttachment emailAttachment : emailAttachmentList) {
                builder.addFormDataPart("files",emailAttachment.getFileName()
                        ,RequestBody.create(MediaType.parse(emailAttachment.getContentType()),emailAttachment.getFile()));
            }
        }
        MultipartBody body = builder.build();
        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .addHeader("token",token)
                .post(body)
                .build();

        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 处理响应内容
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }
    // 附件类，可以不使用，自行修改
    static class EmailAttachment {
        private String fileName;
        private String contentType;
        private byte[] file;

        public String getFileName() {
            return fileName;
        }
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
        public String getContentType() {
            return contentType;
        }
        public void setContentType(String contentType) {
            this.contentType = contentType;
        }
        public byte[] getFile() {
            return file;
        }
        public void setFile(byte[] file) {
            this.file = file;
        }
    }
}
